
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''

g_object_name2 = ''
g_object_name_type = 'random_name'
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        // serverUrl = 'http://88.88.88.88:8888/aliyun-oss-appserver-php/php/get.php'
        // 
        //serverUrl = './php/get.php'
         //serverUrl = 'http://101.37.29.184:8181/ot/php/get.php';

         serverUrl = 'http://touwgf.5iyq0022.com/ot/php/get.php';
        
		
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

//function check_object_radio() {
	
    // var tt = document.getElementsByName('myradio');
    // for (var i = 0; i < tt.length ; i++ )
    // {
    //     if(tt[i].checked)
    //     {
    //         g_object_name_type = tt[i].value;

    //         break;
    //     }
    // }
//}

function get_signature()
{
    // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
   // if (filename != '') { 
    	
   // console.log("111:"+g_object_name2);
  // }
   // console.log("222:"+filename);
    new_multipart_params = {
        'key' : g_object_name2,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function previewImage(file,callback){
        if(!file || !/image\//.test(file.type)) return; //确保文件是图片
        if(file.type=='image/gif'){ //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
            var gif = new moxie.file.FileReader();
            gif.onload = function(){
                callback(gif.result);
                gif.destroy();
                gif = null;
            };
            gif.readAsDataURL(file.getSource());
        }else{
            var image = new moxie.image.Image();
            image.onload = function() {
                image.downsize( 150, 150 );//先压缩一下要预览的图片,宽300，高300
                var imgsrc = image.type=='image/jpeg' ? image.getAsDataURL('image/jpeg',80) : image.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
                callback && callback(imgsrc); //callback传入的参数为预览图片的url
                image.destroy();
                image = null;
            };
            image.load( file.getSource() );
        }
    }

var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    multi_selection: false,
	container: document.getElementById('container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    prevent_duplicates : true,

    filters: {
        mime_types : [ //只允许上传图片和zip文件
        { title : "Image files", extensions : "jpg,gif,png,jpeg" }
        ],
        max_file_size : '10mb', //最大只能上传10mb的文件
        prevent_duplicates : true //不允许选取重复文件
    },

	init: {
		PostInit: function() {
			// document.getElementById('ossfile').innerHTML = '';
			// document.getElementById('postfiles').onclick = function() {
   //          set_upload_param(uploader, '', false);
   //          return false;
			// };
		},

		FilesAdded: function(up, files) {

			 $.each(up.files, function (i, file) {
		        if (up.files.length <= 1) {
		            return;
		        }
		 
		        up.removeFile(file);
		    });

			var len = len = files.length;
                for(var i = 0; i<len; i++){
                    var file_name = files[i].name; //文件名
                    var file_size = files[i].size;//文件大小
                   
                    
                    //构造html来更新UI
                    //var html = '<li id="file-' + files[i].id +'"><p class="file-name">' + file_name + '(' + plupload.formatSize(file_size) + ')' + '</p><p class="progress"></p></li>';
                   // var html = '<li id="file-' + files[i].id +'"><span class="close"></span></li>';
                    //$(html).appendTo('#file-list');
                    //!function(i){
                        previewImage(files[i],function(imgsrc){
                        	$('#images').html('');
                        	$('#images').append('<li class="weui-uploader__file"><img src="'+imgsrc+'" width="100%" height="100%"/></li>');
                        	$('#selectfiles').next().css("left","88px");
                        	
                        	//$('#selectfiles').removeClass('weui-uploader__input-box');
                           // $('#file-'+files[i].id).append('<a><img src="'+ imgsrc +'" /><span class="progress">12</span></a>');
                        })


                     	suffix = get_suffix(file_name)
        				g_object_name2 = "user-dir-prefix/"+key + random_string(10) + suffix
        				set_upload_param(uploader, '', false);
        				document.getElementById('test_s').value = g_object_name2;
                     	//console.log(g_object_name);


                   // }(i);
                   // $("#uploadfiles").trigger('click');
                }
                /*plupload.each(files, function(file) {
                 document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
                 });*/
		},

		BeforeUpload: function(up, file) {

            //check_object_radio();
            set_upload_param(up, file.name, true);
        },

		// UploadProgress: function(up, file) {
		// 	var d = document.getElementById(file.id);
		// 	d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        //  var prog = d.getElementsByTagName('div')[0];
		// 	var progBar = prog.getElementsByTagName('div')[0]
		// 	progBar.style.width= 2*file.percent+'px';
		// 	progBar.setAttribute('aria-valuenow', file.percent);
		// },

		FileUploaded: function(up, file, info) {

            if (info.status == 200)
            {
                //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name) + ' 回调服务器返回的内容是:' + info.response;
                
               // document.getElementById('test_s').value = get_uploaded_object_name(file.name);



               // $('#images').append('<li class="weui-uploader__file"><img src="http://pic1.picyq.com/'+get_uploaded_object_name(file.name)+'" width="100%" height="100%"/></li>');


            }
            else if (info.status == 203)
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response;
            }
            else
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            } 
		},

		Error: function(up, err) {

            if (err.code == -600) {
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
            }
            else if (err.code == -601) {
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
            }
            else if (err.code == -602) {
                document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
            }
            else 
            {
                document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
            }
		}
	}
});

uploader.init();
